package org.xxpay.pay.channel.atoa;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.xxpay.common.http.HttpConfigStorage;
import org.xxpay.common.http.HttpRequestTemplate;
import org.xxpay.common.util.sign.SignUtils;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.util.DateUtil;
import org.xxpay.core.entity.TransOrder;
import org.xxpay.pay.channel.BaseTrans;

import java.util.HashMap;
import java.util.Map;

@Component
public class AtoaTransService extends BaseTrans {
    private final static String logPrefix = "【AtoA】";
    @Override
    public String getChannelName() {
        return AtoaPayConfig.CHANNEL_NAME;
    }

    /**
     * 代付订单
     *
     * @param transOrder
     * @return
     */
    @Override
    public JSONObject trans(TransOrder transOrder) {
        JSONObject retObj = buildRetObj();
        AtoaPayConfig config = new AtoaPayConfig(getTransParam(transOrder));
        Map<String,Object> params = Maps.newHashMap();
        setParams(transOrder,config,params);
        _log.info("{}申请代付请求参数：{}", logPrefix, params.toString());
        HttpConfigStorage httpConfigStorage = new HttpConfigStorage();
        httpConfigStorage.setMaxTotal(5);
        httpConfigStorage.setDefaultMaxPerRoute(3);
        HttpRequestTemplate requestTemplate = new HttpRequestTemplate(httpConfigStorage);
        JSONObject origin = requestTemplate.postForObject(config.getRequestUrl()+ AtoaPayConfig.REQ_TRANS_URL_FIXX, params, JSONObject.class);
        _log.info("{}申请代付响应参数：{}", logPrefix, origin.toJSONString());

        retObj.put("isSuccess", false);
        retObj.put("transOrderId", transOrder.getTransOrderId());
        if (StringUtils.equals("SUCCESS", origin.getString("retCode"))) {
            retObj.put("channelOrderNo", origin.getString("agentpayOrderId"));
            retObj.put("isSuccess", true);
            // 1. 处理中 2. 成功 3. 失败
            retObj.put("status", origin.getIntValue("status"));
            return retObj;
        }
        // 1. 处理中 2. 成功 3. 失败
        retObj.put("status", 3);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, "下单失败[" + origin.getString("retMsg") + "]");
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        return retObj;
    }

    /**
     * 余额查询接口
     *
     * @param payParam
     * @return
     */
    @Override
    public JSONObject balance(String payParam) {
        AtoaPayConfig config = new AtoaPayConfig(payParam);
        JSONObject parameters = new JSONObject();
        parameters.put("mchId", config.getMchId());
        parameters.put("reqTime", DateUtil.getSeqString());
        parameters.put("sign", getSign(parameters,config.getPrivateKey()));
        _log.info("{}代付余额查询请求参数：{}", logPrefix, parameters.toJSONString());
        HttpRequestTemplate requestTemplate = new HttpRequestTemplate(null);
        JSONObject origin = requestTemplate.postForObject(config.getRequestUrl()+ AtoaPayConfig.REQ_TRANS_BALANCE_URL_FIXX, parameters, JSONObject.class);
        _log.info("{}代付余额查询响应参数：{}", logPrefix, origin.toJSONString());
        JSONObject retObj = buildRetObj();
        if (StringUtils.equals("SUCCESS", origin.getString("retCode"))) {
            retObj.put("cashBalance", origin.getString("availableAgentpayBalance"));
            retObj.put("payBalance", origin.getString("agentpayBalance"));
            return retObj;
        }
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, origin.getString("retCode"));
        return retObj;
    }

    /**
     * 订单查询接口
     *
     * @param transOrder
     * @return
     */
    @Override
    public JSONObject query(TransOrder transOrder) {
        AtoaPayConfig config = new AtoaPayConfig(getTransParam(transOrder));
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("mchId", config.getMchId());
        parameters.put("mchOrderNo", transOrder.getMchTransNo());
        parameters.put("reqTime", DateUtil.getSeqString());
        parameters.put("sign", getSign(parameters,config.getPrivateKey()));
        _log.info("{}代付查询请求参数：{}", logPrefix, parameters.toString());
        HttpRequestTemplate requestTemplate = new HttpRequestTemplate(null);
        JSONObject origin = requestTemplate.postForObject(config.getRequestUrl()+ AtoaPayConfig.REQ_TRANS_QUERY_URL_FIXX, parameters, JSONObject.class);
        _log.info("{}代付查询响应参数：{}", logPrefix, origin.toJSONString());
        JSONObject retObj = buildRetObj();
        retObj.put("isSuccess", false);
        retObj.put("transOrderId", transOrder.getTransOrderId());
        if (StringUtils.equals("SUCCESS", origin.getString("retCode"))) {
            retObj.put("channelOrderNo", origin.getString("agentpayOrderId"));
            retObj.put("isSuccess", true);
            // 1. 处理中 2. 成功 3. 失败
            retObj.put("status", origin.getIntValue("status"));
            return retObj;
        }
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, origin.getString("retMsg"));
        retObj.put("channelErrCode", origin.getString("retCode"));
        retObj.put("isSuccess", false);
        return retObj;
    }

    //获取代付请求参数
    private void setParams(TransOrder transOrder, AtoaPayConfig config, Map<String,Object> params){
        params.put("mchId", config.getMchId());
        params.put("mchOrderNo", transOrder.getTransOrderId());
        params.put("amount", transOrder.getAmount());
        params.put("accountAttr", transOrder.getAccountAttr());
        params.put("accountName", transOrder.getAccountName());
        params.put("accountNo", transOrder.getAccountNo());
        params.put("province", transOrder.getProvince());
        params.put("city", transOrder.getCity());
        params.put("bankName", transOrder.getBankName());
        params.put("bankNumber", transOrder.getBankCode());
        params.put("notifyUrl", payConfig.getNotifyTransUrl(getChannelName()));
        params.put("remark", transOrder.getRemarkInfo());
        params.put("extra", transOrder.getExtra());
        params.put("reqTime", DateUtil.getSeqString());
        params.put("sign", getSign(params, config.getPrivateKey()));
    }

    //获取签名
    private String getSign(Map<String, Object> parameters,String key) {
        String signTxt = SignUtils.parameterText(parameters);
        String sign = SignUtils.MD5.createSign(signTxt, "&key=" + key, SignUtils.CHARSET_UTF8);
        return sign.toUpperCase();
    }
}
